package com.xtc.netty.protocol.http;

import com.xtc.netty.protocol.http.enums.Shopping;
import com.xtc.netty.protocol.http.model.Address;
import com.xtc.netty.protocol.http.model.Customer;
import com.xtc.netty.protocol.http.model.Order;
import io.netty.util.CharsetUtil;
import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.IMarshallingContext;
import org.jibx.runtime.IUnmarshallingContext;
import org.jibx.runtime.JiBXException;

import java.io.StringReader;
import java.io.StringWriter;

/**
 * @author Administrator
 */
public class AddressTest {
    public static void main(String[] args) {
        Address address = new Address();
        address.setCity("深圳");
        address.setCountry("西丽");
        address.setPostCode("518000");
        address.setState("0");
        address.setStreet1("西丽南路");
        address.setStreet2("文光村");

        Address convertAddress = decode2Order(encode2Xml(address));

        System.out.println(convertAddress.getCity());
    }

    private static String encode2Xml(Address address) {
        try {
            IBindingFactory factory = BindingDirectory.getFactory(Address.class);
            StringWriter writer = new StringWriter();

            IMarshallingContext context = factory.createMarshallingContext();
            context.setIndent(2);
            context.marshalDocument(address, CharsetUtil.UTF_8.toString(), null, writer);
            String orderXml = writer.toString();
            writer.close();
            System.out.println(orderXml);
            return orderXml;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Address decode2Order(String xmlBody) {
        try {
            IBindingFactory factory = BindingDirectory.getFactory(Address.class);
            StringReader reader = new StringReader(xmlBody);
            IUnmarshallingContext uctx = factory.createUnmarshallingContext();
            return (Address) uctx.unmarshalDocument(reader);
        } catch (JiBXException e) {
            e.printStackTrace();
        }
        return null;
    }
}
